package com.dx.as;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutCompat;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.dx.as.common.log.LogUtil;
import com.dx.as.common.sys.ReflectionUtil;
import com.dx.as.fragment.TFragment;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public abstract class UI extends AppCompatActivity {

    private boolean destroyed = false;
    private static Handler handler;
    private Toolbar toolbar;
    private FrameLayout contentLayout;
    private TextView titleView;
    private TextView btn_right;
    private TextView btn_left;
    private Activity baseActivity;
    private Snackbar snackbar;
    private View toolbarview;
    private ImageView img_right;
    private ImageView img_left;
    @Override
    protected void onStart() {
        super.onStart();
    }

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        getDelegate().setContentView(R.layout.base_activity_layout);
        toolbar =  findViewById(R.id.toolbar);
        toolbarview = findViewById(R.id.toolbarview);
        contentLayout = findViewById(R.id.content);
        titleView = findViewById(R.id.title);
        btn_right =  findViewById(R.id.btn_right);
        btn_left = findViewById(R.id.btn_left);
        img_right =  findViewById(R.id.img_right);
        img_left = findViewById(R.id.img_left);
        setSupportActionBar(toolbar);
        setBackBar(false);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        //如果是后台启动，销毁

//        if ((getIntent().getFlags() & Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT) != 0) {
//            finish();
//            return;
//        }
        if (JWCache.activityList.indexOf(this.getClass()) != JWCache.activityList.lastIndexOf(this.getClass())) {
            finish();
            return;
        }
        onActivityCreate(savedInstanceState);
        setStatusBarLightMode(R.color.white);
        baseActivity = this;
        snackbar = Snackbar.make(contentLayout,"",Snackbar.LENGTH_LONG);
    }

    @Override
    public void setContentView(int layoutResID) {
        contentLayout.removeAllViews();
        getLayoutInflater().inflate(layoutResID, contentLayout, true);
    }

    @Override

    public void setContentView(View view) {
        contentLayout.removeAllViews();
        contentLayout.addView(view);
    }

    public void goToNewActivity(Class<?> clas){
        Intent intent = new Intent(this,clas);
        startActivity(intent);
    }

    public void goToNewActivity(Class<?> cls,Bundle bundle){
        Intent intent = new Intent(this,cls);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    public void goToNewActivityForResult(Class<?> cls,int code){
        goToNewActivityForResult(cls,code,null);
    }

    public void goToNewActivityForResult(Class<?> cls,int code, Bundle bundle){
        Intent intent = new Intent(this,cls);
        if (bundle != null)
            intent.putExtras(bundle);
        startActivityForResult(intent,code);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        contentLayout.addView(view, params);
    }

    public ViewGroup getContentRoot() {
        return contentLayout;
    }

    public void setBackBar(boolean isShow) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(isShow);
    }

    @Override
    public void onBackPressed() {
        invokeFragmentManagerNoteStateNotSaved();
        super.onBackPressed();
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        Configuration config=new Configuration();
        config.setToDefaults();
        res.updateConfiguration(config,res.getDisplayMetrics() );
        return res;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LogUtil.ui("activity: " + getClass().getSimpleName() + " onDestroy()");
        destroyed = true;
    }

    protected abstract void onActivityCreate(Bundle savedInstanceState);

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onNavigateUpClicked();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void setRightBtnEnable(boolean isEnable){
        btn_right.setEnabled(isEnable);
    }

    public void setToolbar(ToolBarOptions options){

        if (options == null) {
            toolbar.setVisibility(View.GONE);
            return;
        }else {
            toolbar.setVisibility(View.VISIBLE);
        }
        if (options.toolbarViewId != 0){
            View view = View.inflate(baseActivity,options.toolbarViewId,null);
            toolbar.removeAllViews();
            toolbar.addView(view,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }else {
            toolbar.removeAllViews();;
            toolbar.addView(toolbarview,new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }

        if (options.titleId != 0) titleView.setText(options.titleId);
        if (!TextUtils.isEmpty(options.titleString)) titleView.setText(options.titleString);
        else titleView.setText("");
        if (options.showLeft){
            img_left.setVisibility(View.VISIBLE);
            btn_left.setVisibility(View.VISIBLE);
            if (options.leftDrawId != 0) {
                btn_left.setBackgroundResource(options.leftDrawId);
            }
            if (options.leftOptionId != 0) btn_left.setText(options.leftOptionId);
            if (!TextUtils.isEmpty(options.leftOptionString)) btn_left.setText(options.leftOptionString);
            if (options.onLeftClickListener != null) {
                btn_left.setOnClickListener(options.onLeftClickListener);
                img_left.setOnClickListener(options.onLeftClickListener);

            }else {
                btn_left.setOnClickListener(onBackClickListener);
                img_left.setOnClickListener(onBackClickListener);
            }

        }else {
            btn_left.setVisibility(View.INVISIBLE);
        }
        if (options.showRight){
            if (options.rightDrawId != 0)  btn_right.setBackgroundResource(options.rightDrawId);
            if (options.rightOptionId != 0) btn_right.setText(options.rightOptionId);
            if (!TextUtils.isEmpty(options.rightOptionString)) btn_right.setText(options.rightOptionString);
            if (options.onRightClickListener != null) btn_right.setOnClickListener(options.onRightClickListener);
        }
        if (options.showRightImg){
            if (options.rightDrawImgId != 0) {
                img_right.setBackgroundResource(options.rightDrawImgId);
                if (options.onRightImgClickListener != null) img_right.setOnClickListener(options.onRightImgClickListener);
            }
        }

        if (options.showLeftImg){
            if (options.leftDrawImgId != 0){
                img_left.setBackgroundResource(options.leftDrawImgId);
                if (options.onLeftImgClickListener != null) img_left.setOnClickListener(options.onLeftImgClickListener);
            }
        }

        img_right.setVisibility(options.showRightImg ? View.VISIBLE : View.GONE);
//        img_right.setOnClickListener(options.onRightClickListener);
    }

    public void showSnackBar(String info){
        snackbar.setText(info);
        snackbar.show();
    }

    private View.OnClickListener onBackClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onNavigateUpClicked();
        }
    };

    public Toolbar getToolBar() {
        return toolbar;
    }

    public int getToolBarHeight() {
        if (toolbar != null) {
            return toolbar.getHeight();
        }
        return 0;
    }

    public void onNavigateUpClicked() {
        onBackPressed();
    }

    @Override
    public void setTitle(CharSequence title) {
        if (title != null) {
            titleView.setText(title);
        }
    }

    @Override
    public void setTitle(int titleId) {
        if (titleId != 0) {
            titleView.setText(titleId);
        }
    }

    protected final Handler getHandler() {
        if (handler == null) {
            handler = new Handler(getMainLooper());
        }
        return handler;
    }

    protected void showKeyboard(boolean isShow) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isShow) {
            if (getCurrentFocus() == null) {
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
            } else {
                imm.showSoftInput(getCurrentFocus(), 0);
            }
        } else {
            if (getCurrentFocus() != null) {
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 延时弹出键盘
     *
     * @param focus 键盘的焦点项
     */
    protected void showKeyboardDelayed(View focus) {
        final View viewToFocus = focus;
        if (focus != null) {
            focus.requestFocus();
        }

        getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if (viewToFocus == null || viewToFocus.isFocused()) {
                    showKeyboard(true);
                }
            }
        }, 200);
    }


    public boolean isDestroyedCompatible() {
        if (Build.VERSION.SDK_INT >= 17) {
            return isDestroyedCompatible17();
        } else {
            return destroyed || super.isFinishing();
        }
    }

    @TargetApi(17)
    private boolean isDestroyedCompatible17() {
        return super.isDestroyed();
    }



    protected boolean displayHomeAsUpEnabled() {
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_MENU:
                return onMenuKeyDown();
            default:
                return super.onKeyDown(keyCode, event);
        }
    }

    protected boolean onMenuKeyDown() {
        return false;
    }

    private void invokeFragmentManagerNoteStateNotSaved() {
        FragmentManager fm = getFragmentManager();
        ReflectionUtil.invokeMethod(fm, "noteStateNotSaved", null);
    }

    protected boolean isCompatible(int apiLevel) {
        return Build.VERSION.SDK_INT >= apiLevel;
    }

    protected <T extends View> T findView(int resId) {
        return (T) (findViewById(resId));
    }


    /**
     * fragment management
     */
    public TFragment addFragment(TFragment fragment) {
        List<TFragment> fragments = new ArrayList<TFragment>(1);
        fragments.add(fragment);

        List<TFragment> fragments2 = addFragments(fragments);
        return fragments2.get(0);
    }

    public List<TFragment> addFragments(List<TFragment> fragments) {
        List<TFragment> fragments2 = new ArrayList<TFragment>(fragments.size());

        FragmentManager fm = getFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();

        boolean commit = false;
        for (int i = 0; i < fragments.size(); i++) {
            // install
            TFragment fragment = fragments.get(i);
            int id = fragment.getContainerId();

            // exists
            TFragment fragment2 = (TFragment) fm.findFragmentById(id);

            if (fragment2 == null) {
                fragment2 = fragment;
                transaction.add(id, fragment);
                commit = true;
            }

            fragments2.add(i, fragment2);
        }

        if (commit) {
            try {
                transaction.commitAllowingStateLoss();
            } catch (Exception e) {

            }
        }

        return fragments2;
    }

    public TFragment switchContent(TFragment fragment) {
        return switchContent(fragment, false);
    }

    protected TFragment switchContent(TFragment fragment, boolean needAddToBackStack) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        fragmentTransaction.replace(fragment.getContainerId(), fragment);
        if (needAddToBackStack) {
            fragmentTransaction.addToBackStack(null);
        }
        try {
            fragmentTransaction.commitAllowingStateLoss();
        } catch (Exception e) {

        }

        return fragment;
    }

    private void setStatusBarLightMode(int color) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //如果是6.0以上将状态栏文字改为黑色，并设置状态栏颜色
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(getResources().getColor(color));
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            //fitsSystemWindow 为 false, 不预留系统栏位置.
            ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
            View mChildView = mContentView.getChildAt(0);
            if (mChildView != null) {
                ViewCompat.setFitsSystemWindows(mChildView, true);
                ViewCompat.requestApplyInsets(mChildView);
            }
        }
    }

}
